package au.com.handsunited.web.controller.entity;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import au.com.handsunited.model.BaseEntity;
import au.com.handsunited.model.message.Message;
import au.com.handsunited.service.EntityService;
import au.com.handsunited.web.command.MessageCommand;
import au.com.handsunited.web.session.SessionSupport;

/**
 *
 * @author Arun Chandrasekhar
 */
public class PostMessageController extends SimpleFormController {

	private EntityService entityService;

	private static Logger logger = LoggerFactory.getLogger(PostMessageController.class);


	/**
	 *
	 */
	public PostMessageController() {
		setCommandClass(MessageCommand.class);
	}

	/**
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		ModelAndView mav = null;

		MessageCommand messageCommand = (MessageCommand) command;

		Message message = messageCommand.getMessage();
		message.setPoster(SessionSupport.getUser(request));

		BaseEntity messageRecipient = entityService.getEntity(messageCommand.getRecipientId());

		messageRecipient = entityService.postMessage(messageRecipient, message);

		setSuccessView("/" + messageRecipient.getEntityType() + "/profile");

		mav = new ModelAndView(getSuccessView(), "entity", messageRecipient);

		return mav;
	}

	/**
	 * @param entityService the entityService to set
	 */
	public void setEntityService(EntityService entityService) {
		this.entityService = entityService;
	}

}
